const { getPagination } = require('@utils/tools');

const address = require('./address.model');

module.exports = {
  async addrAdd(data) {
    try {
      const res = await address.create(data);

      return res.dataValues;
    } catch (error) {
      console.log(`\x1B[41m ${error} \x1B[0m`);
    }
  },
  async addrGetList({ page_size, page_num, user }) {
    const { offset, limit } = getPagination(page_num, page_size);

    try {
      const { rows, count } = await address.findAndCountAll({
        offset,
        limit,
        attributes: { exclude: ['createdAt', 'updatedAt', 'deletedAt'] },
        where: {
          user_id: user.id,
        },
      });

      return { rows, count, page_size, page_num };
    } catch (error) {
      console.log(`\x1B[45m ${error} \x1B[0m`);
    }
  },
  async addrSetDefault({ id, user_id }) {
    try {
      await address.update(
        { is_default: false },
        {
          where: { user_id },
        }
      );

      const [count] = await address.update(
        { is_default: true },
        {
          where: { user_id, id },
        }
      );

      return count > 0;
    } catch (error) {
      console.log(`\x1B[41m ${error} \x1B[0m`);
    }
  },
  async addrUpdate({ id, user_id, values }) {
    try {
      const [count] = await address.update(values, {
        where: { user_id, id },
      });

      return count > 0;
    } catch (error) {
      console.log(`\x1B[41m ${error} \x1B[0m`);
    }
  },
};
